package com.example.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pojo.Dev;
import com.example.service.DevService;
import com.example.zqwl.dev_conn_info;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//import static com.sun.xml.internal.ws.handler.HandlerProcessor.logger;

@Component
public class InServerHandler extends SimpleChannelInboundHandler<String>{
    public static Map<String, Channel> channelMap = new ConcurrentHashMap<String, Channel>();
    public static Map<String, String> msgMap = new ConcurrentHashMap<String, String>();
    public static Map<String, String> imei_ip_Map = new ConcurrentHashMap<String, String>();
    public static Map<String, dev_conn_info> ip_conn_Map = new ConcurrentHashMap<String, dev_conn_info>();
    @Autowired
    protected DevService devService;
    private static InServerHandler  inServerHandler ;
    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        inServerHandler = this;
        inServerHandler.devService = this.devService;
        // 初使化时将已静态化的testService实例化
    }

    //定义一个channle 组，管理所有的channel
    //GlobalEventExecutor.INSTANCE) 是全局的事件执行器，是一个单例
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    /**
     * 有客户端与服务器发生连接时执行此方法
     * 1.打印提示信息
     * 2.将客户端保存到 channelGroup 中
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel ch = ctx.channel();
        System.err.println("有新的客户端与服务器发生连接。客户端地址：" + ch.remoteAddress());
        channelGroup.add(ch);
        System.out.println(ch);
    }

    /**
     * 当有客户端与服务器断开连接时执行此方法，此时会自动将此客户端从 channelGroup 中移除
     * 1.打印提示信息
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String address=""+channel.remoteAddress();
        QueryWrapper<Dev> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("address",address.substring(1));
        inServerHandler.devService.remove(queryWrapper);
        System.err.println("有客户端与服务器断开连接。客户端地址：" + channel.remoteAddress());
    }

    /**
     * 表示channel 处于活动状态
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 处于活动状态");
    }

    /**
     * 表示channel 处于不活动状态
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 处于不活动状态");
    }

    /**
     * 读取到客户端发来的数据
     * */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		// TODO Auto-generated method stub
		//获取到当前channel
        Channel channel = ctx.channel();
        //System.err.println(JSON.parseObject(String.valueOf(channel)));
        String address=""+channel.remoteAddress();
        System.out.println(address.substring(1));
        Dev dev1 =RXD(address.substring(1),msg,0);
        System.err.println("有客户端发来的数据。地址：" + channel.remoteAddress() + " 内容：" + msg);

	}
    public Dev RXD( String address, String msg,  int identity) {
        QueryWrapper<Dev> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("address",address);
        Dev dev1 =inServerHandler.devService.getOne(queryWrapper);
        if(dev1==null){
            Dev dev = new Dev();
            dev.setAddress(address);
            dev.setIdentity(identity);//客户端发送消息
            dev.setMsg(msg);//JSON信息
            inServerHandler.devService.save(dev);
            return dev;
        }
        Dev dev = new Dev();
        dev.setAddress(address);
        dev.setIdentity(identity);//客户端发送消息
        dev.setMsg(msg);//JSON信息
        inServerHandler.devService.updateDevice(dev);
        return dev;
    }
	/**
     * 处理异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常。异常信息："+cause.getMessage());
        //关闭通道
        ctx.close();
    }

    /**
     * 数据存入数据库
     * @param msg
     * @return
     */
    /*public static String insertMysql(String msg){
        String str;
        // 传递sql语句
        Statement stt;
        Connection conn = null;
        String sql = "insert into env_data(datas) values ('"+msg+"')";  //env_data()一定要连起来不然会有错误
        try {
            conn = mysqlimages.getConn();  //一个连接数据库的方法，这就不贴了，很简单的
            //获取Statement对象
            stt = conn.createStatement();
            //执行sql语句
            stt.executeUpdate(sql);
            logger.info(">>>插入数据库成功");
            str = Const.SECCESS;
        } catch (Exception e) {
            logger.error("<<<插入数据错误--"+e.getMessage());
            str = Const.ERROR;
        }finally {
            try {
                conn.close();
            } catch (SQLException e) {
                logger.error("<<<关闭数据库错误"+e.getMessage());
            }
        }
        return str;
    }*/
}


